/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sqlserver;

/**
 *
 * @author BEHIEN
 */
import java.util.ArrayList;
import java.util.List;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.*;

public class CreateDatabase {
    public static int CreateDatabase(Database db) {
		if (db == null || db.getDbName() == "")
			return MetaFile.ErrorInvalidAgrument;
		Document doc = MetaFile.LoadDoc();
		if (doc == null)
			return MetaFile.ErrorLoading;
		if (CheckDatabaseExist(db.getDbName()))
			return MetaFile.ErrorExisted;

		Element root = doc.getDocumentElement();
		Element newDBNode = doc.createElement("Database");

		Attr attr = doc.createAttribute("Name");
		attr.setValue(db.getDbName());
		newDBNode.setAttributeNode(attr);

		Element tbs = doc.createElement("Tables");
		newDBNode.appendChild(tbs);

		root.appendChild(newDBNode);
		if (MetaFile.Save(doc) == MetaFile.Success) {
			return MetaFile.Success;
		} else {
			return MetaFile.ErrorUnknown;
		}
	}

	public static List<Database> getAllDatabase() {
		try {
			Document doc = MetaFile.LoadDoc();
			XPath xpath = XPathFactory.newInstance().newXPath();
			XPathExpression expr = xpath.compile("//Database");
			NodeList listNodes = (NodeList) expr.evaluate(doc,
					XPathConstants.NODESET);
			if (listNodes != null) {
				List<Database> result = new ArrayList<Database>();
				for (int i = 0; i < listNodes.getLength(); i++) {
					Element itemNode = (Element) listNodes.item(i);
					Database item = new Database(itemNode.getAttribute("Name"));
					result.add(item);
				}
				return result;
			}
		} catch (Exception e) {
			return null;
		}
		return null;

	}

	public static Database getDatabaseByName(String dbName) {
		try {
			Document doc = MetaFile.LoadDoc();
			XPath xpath = XPathFactory.newInstance().newXPath();
			XPathExpression expr = xpath.compile("//Database[@Name='" + dbName
					+ "']");
			Node resultNode = (Node) expr.evaluate(doc, XPathConstants.NODE);
			if (resultNode != null) {
				Database result = new Database(dbName);
				return result;
			}
		} catch (Exception e) {
			return null;
		}
		return null;
	}

	public static boolean CheckDatabaseExist(String dbName) {
		try {
			Document doc = MetaFile.LoadDoc();
			XPath xpath = XPathFactory.newInstance().newXPath();
			// XPath Query for showing all nodes value
			XPathExpression expr = xpath.compile("//Database[@Name='" + dbName
					+ "']");
			Node result = (Node) expr.evaluate(doc, XPathConstants.NODE);
			if (result != null)
				return true;
		} catch (Exception e) {
			return false;
		}
		return false;
	}
}
